package com.ship.dispatch.controller;

import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.http.HttpRequest;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ship.common.core.domain.R;
import com.ship.common.core.exception.BusException;
import com.ship.common.core.exception.ServiceException;
import com.ship.common.core.utils.FileUtils;
import com.ship.common.core.utils.HttpRequestUtil;
import com.ship.common.core.validate.Update;
import com.ship.common.core.web.domain.BaseResultCode;
import com.ship.common.core.web.domain.JsonResult;
import com.ship.common.log.annotation.Log;
import com.ship.common.log.enums.BusinessType;
import com.ship.dispatch.bean.SpOverhaul;
import com.ship.dispatch.bean.fob.SpFobFileRecord;
import com.ship.dispatch.bo.SpOverhaulBO;
import com.ship.dispatch.model.Vo.SpArrangeVo;
import com.ship.dispatch.service.SpOverhaulService;
import com.ship.dispatch.service.fob.SpFobFileRecordService;
import com.ship.dispatch.vo.SpOverhaulVo;
import com.ship.system.api.RemoteFileService;
import com.ship.system.api.domain.SysFile;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.codec.multipart.FilePart;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.io.InputStream;
import java.io.SequenceInputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/spOverhaul")
@Api(value = "disSpOverhaul", tags = "船舶检修前端控制器")
public class SpOverhaulController {

    @Autowired
    SpOverhaulService spOverhaulService;

    @Autowired
    SpFobFileRecordService spFobFileRecordService;

    @Autowired
    private RemoteFileService remoteFileService;

    @Value("${file_server.host}")
    private String fileServerHost;

    private static final String FILE_UPLOAD_PATH = "/group1/upload";
    /**
     * 添加船舶检修信息
     * @param spOverhaul
     * @return
     */
    @PostMapping("/add")
    public JsonResult schemeAdd(@RequestBody SpOverhaul spOverhaul) {
        return spOverhaulService.schemeAdd(spOverhaul);
    }

    /**
     * 分页查询
     * @param spOverhaulBO
     * @return
     */
    @PostMapping("/page")
    public JsonResult<SpOverhaul> getSchemeDetailPage(@RequestBody @Validated SpOverhaulBO spOverhaulBO) {
        JsonResult<SpOverhaul> page = spOverhaulService.getListInfo(spOverhaulBO);
        return page;
    }

    /**
     * 查询所有船只
     * @return
     */
    @PostMapping("/shipList")
    public JsonResult<Object> shipList() {
        return spOverhaulService.getshipList();
    }

    /**
     * 根据id删除
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public JsonResult delete(@PathVariable Long id) {
        spOverhaulService.delApply(id);
        return JsonResult.success();
    }

    /**
     * 导出
     * @param spOverhaulVo
     * @return
     * @throws IOException
     */
    @PostMapping("/export")
    public JsonResult<Object> export(@RequestBody SpOverhaulVo spOverhaulVo) throws IOException {
        String url = spOverhaulService.export(spOverhaulVo);
        return JsonResult.success(url);
    }

    /**
     * 上传文件
     * @param file
     * @return
     */
    @PostMapping("/uploadFile")
    @Log(title = "上传文件",businessType = BusinessType.IMPORT)
    public JsonResult uploadFile(@RequestParam("file") MultipartFile file) {
        FileUtils.checkFileName(file);
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }
        String name = file.getOriginalFilename();

        String url = upload(file);

        SpFobFileRecord spFobFileRecord = new SpFobFileRecord();
        spFobFileRecord.setPath(url);
        spFobFileRecord.setName(name);
        spFobFileRecord.setFileType("船舶检修");

        spFobFileRecordService.save(spFobFileRecord);
        Long id = spFobFileRecord.getId();

        return JsonResult.success(id.toString());
    }

    @PostMapping("/supplyFile")
    @Log(title = "上传文件",businessType = BusinessType.IMPORT)
    public JsonResult supply(@RequestParam("file") MultipartFile file,String overhaulId) {
        FileUtils.checkFileName(file);
        if (file.isEmpty()) {
            throw new IllegalArgumentException("上传的文件为空");
        }
        String name = file.getOriginalFilename();
        String url = upload(file);

        SpFobFileRecord spFobFileRecord = new SpFobFileRecord();
        spFobFileRecord.setPath(url);
        spFobFileRecord.setName(name);
        spFobFileRecord.setFileType("船舶检修");
//            spFobFileRecord.setOverhaulId(Long.valueOf(overhaulId));

        spFobFileRecordService.save(spFobFileRecord);
        String id = String.valueOf(spFobFileRecord.getId());

        return JsonResult.success(id);
    }
    /**
     * 详情
     * @param id
     * @return
     */
    @GetMapping
    public JsonResult<SpOverhaul> detail(Long id) {
        return JsonResult.success(spOverhaulService.detail(id));
    }

    /**
     * 修改
     * @param spOverhaul
     * @return
     */
    @PutMapping
    public JsonResult<Object> update(@RequestBody @Validated(Update.class) SpOverhaul spOverhaul) {
        spOverhaulService.updateCon(spOverhaul);
        return JsonResult.success();
    }

    /**
     * 获取船舶和对应的imo
     * @return
     */
    @GetMapping("/shipAndImo")
    public JsonResult shipAndImo() {
        List<Map<String, String>> result = spOverhaulService.shipAndImo();
        return JsonResult.success(result);
    }

    @GetMapping("/nowShipAndImo")
    public JsonResult nowShipAndImo() {
        List<Map<String, String>> result = spOverhaulService.nowShipAndImo();
        List<Map<String, String>> uniqueList = result.stream()
                .collect(Collectors.toMap(
                        m -> m.get("nameOfVessel") + "-" + m.get("imo"),
                        m -> m,
                        (existing, replacement) -> existing
                ))
                .values()
                .stream()
                .collect(Collectors.toList());
        return JsonResult.success(uniqueList);
    }


    /**
     * 上传附件M
     * @return
     */
    public String upload(MultipartFile file){
        FileUtils.checkFileName(file);
        R<SysFile> result1 = remoteFileService.upload(file);
        if(result1.getCode() != R.SUCCESS){
            throw new BusException("文件服务器连接失败", BaseResultCode.GENERAL_ERROR);
        }
        String result = result1.getData().getHttpsUrl();;
        return result;
    }

}
